home *** CD-ROM | disk | FTP | other *** search
/ Freelog 115 / FreelogNo115-MaiJuin2013.iso / Internet / Filezilla Server / FileZilla_Server-0_9_41.exe / source / AsyncSocketExLayer.cpp < prev    next >
C/C++ Source or Header  |  2011-11-06  |  27KB  |  1,015 lines

  1. /*CAsyncSocketEx by Tim Kosse (Tim.Kosse@gmx.de)
  2.             Version 1.1 (2002-11-01)
  3. --------------------------------------------------------
  4.  
  5. Introduction:
  6. -------------
  7.  
  8. CAsyncSocketEx is a replacement for the MFC class CAsyncSocket.
  9. This class was written because CAsyncSocket is not the fastest WinSock
  10. wrapper and it's very hard to add new functionality to CAsyncSocket
  11. derived classes. This class offers the same functionality as CAsyncSocket.
  12. Also, CAsyncSocketEx offers some enhancements which were not possible with
  13. CAsyncSocket without some tricks.
  14.  
  15. How do I use it?
  16. ----------------
  17. Basically exactly like CAsyncSocket.
  18. To use CAsyncSocketEx, just replace all occurrences of CAsyncSocket in your
  19. code with CAsyncSocketEx, if you did not enhance CAsyncSocket yourself in
  20. any way, you won't have to change anything else in your code.
  21.  
  22. Why is CAsyncSocketEx faster?
  23. -----------------------------
  24.  
  25. CAsyncSocketEx is slightly faster when dispatching notification event messages.
  26. First have a look at the way CAsyncSocket works. For each thread that uses
  27. CAsyncSocket, a window is created. CAsyncSocket calls WSAAsyncSelect with
  28. the handle of that window. Until here, CAsyncSocketEx works the same way.
  29. But CAsyncSocket uses only one window message (WM_SOCKET_NOTIFY) for all
  30. sockets within one thread. When the window recieve WM_SOCKET_NOTIFY, wParam
  31. contains the socket handle and the window looks up an CAsyncSocket instance
  32. using a map. CAsyncSocketEx works differently. It's helper window uses a
  33. wide range of different window messages (WM_USER through 0xBFFF) and passes
  34. a different message to WSAAsyncSelect for each socket. When a message in
  35. the specified range is received, CAsyncSocketEx looks up the pointer to a
  36. CAsyncSocketEx instance in an Array using the index of message - WM_USER.
  37. As you can see, CAsyncSocketEx uses the helper window in a more efficient
  38. way, as it don't have to use the slow maps to lookup it's own instance.
  39. Still, speed increase is not very much, but it may be noticeable when using
  40. a lot of sockets at the same time.
  41. Please note that the changes do not affect the raw data throughput rate,
  42. CAsyncSocketEx only dispatches the notification messages faster.
  43.  
  44. What else does CAsyncSocketEx offer?
  45. ------------------------------------
  46.  
  47. CAsyncSocketEx offers a flexible layer system. One example is the proxy layer.
  48. Just create an instance of the proxy layer, configure it and add it to the layer
  49. chain of your CAsyncSocketEx instance. After that, you can connect through
  50. proxies.
  51. Benefit: You don't have to change much to use the layer system.
  52. Another layer that is currently in development is the SSL layer to establish
  53. SSL encrypted connections.
  54.  
  55. License
  56. -------
  57.  
  58. Feel free to use this class, as long as you don't claim that you wrote it
  59. and this copyright notice stays intact in the source files.
  60. If you use this class in commercial applications, please send a short message
  61. to tim.kosse@gmx.de
  62. */
  63. #include "stdafx.h"
  64. #include "AsyncSocketExLayer.h"
  65.  
  66. #include "AsyncSocketEx.h"
  67.  
  68. #ifdef _DEBUG
  69.     #undef THIS_FILE
  70.     static char THIS_FILE[]=__FILE__;
  71.     #ifdef DEBUG_NEW
  72.         #define new DEBUG_NEW
  73.     #endif
  74. #endif
  75.  
  76. #define WM_SOCKETEX_NOTIFY (WM_USER+3)
  77.  
  78.  
  79. //////////////////////////////////////////////////////////////////////
  80. // Konstruktion/Destruktion
  81. //////////////////////////////////////////////////////////////////////
  82.  
  83. CAsyncSocketExLayer::CAsyncSocketExLayer()
  84. {
  85.     m_pOwnerSocket = NULL;
  86.     m_pNextLayer = NULL;
  87.     m_pPrevLayer = NULL;
  88.  
  89.     m_nLayerState = notsock;
  90.     m_nCriticalError=0;
  91.  
  92.     m_nPendingEvents = 0;
  93.  
  94.     m_nFamily = AF_UNSPEC;
  95.     m_lpszSocketAddress = 0;
  96.  
  97.     m_nextAddr = 0;
  98.     m_addrInfo = 0;
  99. }
  100.  
  101. CAsyncSocketExLayer::~CAsyncSocketExLayer()
  102. {
  103.     delete [] m_lpszSocketAddress;
  104. }
  105.  
  106. CAsyncSocketExLayer *CAsyncSocketExLayer::AddLayer(CAsyncSocketExLayer *pLayer, CAsyncSocketEx *pOwnerSocket)
  107. {
  108.     ASSERT(pLayer);
  109.     ASSERT(pOwnerSocket);
  110.     if (m_pNextLayer)
  111.     {
  112.         return m_pNextLayer->AddLayer(pLayer, pOwnerSocket);
  113.     }
  114.     else
  115.     {
  116.         ASSERT(m_pOwnerSocket==pOwnerSocket);
  117.         pLayer->Init(this, m_pOwnerSocket);
  118.         m_pNextLayer=pLayer;
  119.     }
  120.     return m_pNextLayer;
  121. }
  122.  
  123. int CAsyncSocketExLayer::Receive(void* lpBuf, int nBufLen, int nFlags /*=0*/)
  124. {
  125.     return ReceiveNext(lpBuf, nBufLen, nFlags);
  126. }
  127.  
  128. int CAsyncSocketExLayer::Send(const void* lpBuf, int nBufLen, int nFlags /*=0*/)
  129. {
  130.     return SendNext(lpBuf, nBufLen, nFlags);
  131. }
  132.  
  133.  
  134. void CAsyncSocketExLayer::OnReceive(int nErrorCode)
  135. {
  136.     if (m_pPrevLayer)
  137.         m_pPrevLayer->OnReceive(nErrorCode);
  138.     else
  139.         if (m_pOwnerSocket->m_lEvent&FD_READ)
  140.             m_pOwnerSocket->OnReceive(nErrorCode);
  141. }
  142.  
  143. void CAsyncSocketExLayer::OnSend(int nErrorCode)
  144. {
  145.     if (m_pPrevLayer)
  146.         m_pPrevLayer->OnSend(nErrorCode);
  147.     else
  148.         if (m_pOwnerSocket->m_lEvent&FD_WRITE)
  149.             m_pOwnerSocket->OnSend(nErrorCode);
  150. }
  151.  
  152. void CAsyncSocketExLayer::OnConnect(int nErrorCode)
  153. {
  154.     TriggerEvent(FD_CONNECT, nErrorCode, TRUE);
  155. }
  156.  
  157. void CAsyncSocketExLayer::OnAccept(int nErrorCode)
  158. {
  159.     if (m_pPrevLayer)
  160.         m_pPrevLayer->OnAccept(nErrorCode);
  161.     else
  162.         if (m_pOwnerSocket->m_lEvent&FD_ACCEPT)
  163.             m_pOwnerSocket->OnAccept(nErrorCode);
  164. }
  165.  
  166. void CAsyncSocketExLayer::OnClose(int nErrorCode)
  167. {
  168.     if (m_pPrevLayer)
  169.         m_pPrevLayer->OnClose(nErrorCode);
  170.     else
  171.         if (m_pOwnerSocket->m_lEvent&FD_CLOSE)
  172.             m_pOwnerSocket->OnClose(nErrorCode);
  173. }
  174.  
  175. BOOL CAsyncSocketExLayer::TriggerEvent(long lEvent, int nErrorCode, BOOL bPassThrough /*=FALSE*/ )
  176. {
  177.     ASSERT(m_pOwnerSocket);
  178.     if (m_pOwnerSocket->m_SocketData.hSocket==INVALID_SOCKET)
  179.         return FALSE;
  180.  
  181.     if (!bPassThrough)
  182.     {
  183.         if (m_nPendingEvents & lEvent)
  184.             return TRUE;
  185.  
  186.         m_nPendingEvents |= lEvent;
  187.     }
  188.  
  189.     if (lEvent & FD_CONNECT)
  190.     {
  191.         ASSERT(bPassThrough);
  192.         if (!nErrorCode)
  193.             ASSERT(bPassThrough && (GetLayerState()==connected || GetLayerState()==attached));
  194.         else if (nErrorCode)
  195.         {
  196.             SetLayerState(aborted);
  197.             m_nCriticalError=nErrorCode;
  198.         }
  199.     }
  200.     else if (lEvent & FD_CLOSE)
  201.     {
  202.         if (!nErrorCode)
  203.             SetLayerState(closed);
  204.         else
  205.         {
  206.             SetLayerState(aborted);
  207.             m_nCriticalError = nErrorCode;
  208.         }
  209.     }
  210.     ASSERT(m_pOwnerSocket->m_pLocalAsyncSocketExThreadData);
  211.     ASSERT(m_pOwnerSocket->m_pLocalAsyncSocketExThreadData->m_pHelperWindow);
  212.     ASSERT(m_pOwnerSocket->m_SocketData.nSocketIndex!=-1);
  213.     t_LayerNotifyMsg *pMsg=new t_LayerNotifyMsg;
  214.     pMsg->hSocket = m_pOwnerSocket->m_SocketData.hSocket;
  215.     pMsg->lEvent = ( lEvent % 0xffff ) + ( nErrorCode << 16);
  216.     pMsg->pLayer=bPassThrough?m_pPrevLayer:this;
  217.     BOOL res=PostMessage(m_pOwnerSocket->GetHelperWindowHandle(), WM_USER, (WPARAM)m_pOwnerSocket->m_SocketData.nSocketIndex, (LPARAM)pMsg);
  218.     if (!res)
  219.         delete pMsg;
  220.     return res;
  221. }
  222.  
  223. void CAsyncSocketExLayer::Close()
  224. {
  225.     CloseNext();
  226. }
  227.  
  228. void CAsyncSocketExLayer::CloseNext()
  229. {
  230.     if (m_addrInfo)
  231.         m_pOwnerSocket->p_freeaddrinfo(m_addrInfo);
  232.     m_nextAddr = 0;
  233.     m_addrInfo = 0;
  234.  
  235.     m_nPendingEvents = 0;
  236.  
  237.     SetLayerState(notsock);
  238.     if (m_pNextLayer)
  239.         m_pNextLayer->Close();
  240. }
  241.  
  242. BOOL CAsyncSocketExLayer::Connect(LPCTSTR lpszHostAddress, UINT nHostPort)
  243. {
  244.     return ConnectNext(lpszHostAddress, nHostPort);
  245. }
  246.  
  247. BOOL CAsyncSocketExLayer::Connect( const SOCKADDR* lpSockAddr, int nSockAddrLen )
  248. {
  249.     return ConnectNext(lpSockAddr, nSockAddrLen);
  250. }
  251.  
  252. int CAsyncSocketExLayer::SendNext(const void *lpBuf, int nBufLen, int nFlags /*=0*/)
  253. {
  254.     if (m_nCriticalError)
  255.     {
  256.         WSASetLastError(m_nCriticalError);
  257.         return SOCKET_ERROR;
  258.     }
  259.     else if (GetLayerState()==notsock)
  260.     {
  261.         WSASetLastError(WSAENOTSOCK);
  262.         return SOCKET_ERROR;
  263.     }
  264.     else if (GetLayerState()==unconnected || GetLayerState()==connecting || GetLayerState()==listening)
  265.     {
  266.         WSASetLastError(WSAENOTCONN);
  267.         return SOCKET_ERROR;
  268.     }
  269.  
  270.     if (!m_pNextLayer)
  271.     {
  272.         ASSERT(m_pOwnerSocket);
  273.         return send(m_pOwnerSocket->GetSocketHandle(), (LPSTR)lpBuf, nBufLen, nFlags);
  274.     }
  275.     else
  276.         return m_pNextLayer->Send(lpBuf, nBufLen, nFlags);
  277. }
  278.  
  279. int CAsyncSocketExLayer::ReceiveNext(void *lpBuf, int nBufLen, int nFlags /*=0*/)
  280. {
  281.     if (m_nCriticalError)
  282.     {
  283.         WSASetLastError(m_nCriticalError);
  284.         return SOCKET_ERROR;
  285.     }
  286.     else if (GetLayerState()==notsock)
  287.     {
  288.         WSASetLastError(WSAENOTSOCK);
  289.         return SOCKET_ERROR;
  290.     }
  291.     else if (GetLayerState()==unconnected || GetLayerState()==connecting || GetLayerState()==listening)
  292.     {
  293.         WSASetLastError(WSAENOTCONN);
  294.         return SOCKET_ERROR;
  295.     }
  296.  
  297.     if (!m_pNextLayer)
  298.     {
  299.         ASSERT(m_pOwnerSocket);
  300.         return recv(m_pOwnerSocket->GetSocketHandle(), (LPSTR)lpBuf, nBufLen, nFlags);
  301.     }
  302.     else
  303.         return m_pNextLayer->Receive(lpBuf, nBufLen, nFlags);
  304. }
  305.  
  306. BOOL CAsyncSocketExLayer::ConnectNext(LPCTSTR lpszHostAddress, UINT nHostPort)
  307. {
  308.     ASSERT(GetLayerState()==unconnected);
  309.     ASSERT(m_pOwnerSocket);
  310.     BOOL res;
  311.     if (m_pNextLayer)
  312.         res = m_pNextLayer->Connect(lpszHostAddress, nHostPort);
  313.     else if (m_nFamily == AF_INET)
  314.     {
  315.         USES_CONVERSION;
  316.  
  317.         ASSERT(lpszHostAddress != NULL);
  318.  
  319.         SOCKADDR_IN sockAddr;
  320.         memset(&sockAddr,0,sizeof(sockAddr));
  321.  
  322.         LPSTR lpszAscii = T2A((LPTSTR)lpszHostAddress);
  323.         sockAddr.sin_family = AF_INET;
  324.         sockAddr.sin_addr.s_addr = inet_addr(lpszAscii);
  325.  
  326.         if (sockAddr.sin_addr.s_addr == INADDR_NONE)
  327.         {
  328.             LPHOSTENT lphost;
  329.             lphost = gethostbyname(lpszAscii);
  330.             if (lphost != NULL)
  331.                 sockAddr.sin_addr.s_addr = ((LPIN_ADDR)lphost->h_addr)->s_addr;
  332.             else
  333.             {
  334.                 WSASetLastError(WSAEINVAL);
  335.                 res = FALSE;
  336.             }
  337.         }
  338.  
  339.         sockAddr.sin_port = htons((u_short)nHostPort);
  340.  
  341.         res = (SOCKET_ERROR != connect(m_pOwnerSocket->GetSocketHandle(), (SOCKADDR*)&sockAddr, sizeof(sockAddr)) );
  342.     }
  343.     else if (m_nFamily == AF_INET6 || m_nFamily == AF_UNSPEC)
  344.     {
  345.         if (!m_pOwnerSocket->p_getaddrinfo)
  346.         {
  347.             WSASetLastError(WSAEPROTONOSUPPORT);
  348.             return FALSE;
  349.         }
  350.         USES_CONVERSION;
  351.  
  352.         ASSERT(lpszHostAddress != NULL);
  353.  
  354.         addrinfo hints, *res0, *res1;
  355.         SOCKET hSocket;
  356.         int error;
  357.         char port[10];
  358.  
  359.         m_pOwnerSocket->p_freeaddrinfo(m_addrInfo);
  360.         m_nextAddr = 0;
  361.         m_addrInfo = 0;
  362.  
  363.         memset(&hints, 0, sizeof(addrinfo));
  364.         hints.ai_family = m_nFamily;
  365.         hints.ai_socktype = SOCK_STREAM;
  366.         hints.ai_flags = 0;
  367.         _snprintf(port, 9, "%lu", nHostPort);
  368.         error = m_pOwnerSocket->p_getaddrinfo(T2CA(lpszHostAddress), port, &hints, &res0);
  369.         if (error)
  370.             return FALSE;
  371.  
  372.         for (res1 = res0; res1; res1 = res1->ai_next)
  373.         {
  374.             if (m_nFamily == AF_UNSPEC)
  375.                 hSocket = socket(res1->ai_family, res1->ai_socktype, res1->ai_protocol);
  376.             else
  377.                 hSocket = m_pOwnerSocket->GetSocketHandle();
  378.  
  379.             if (INVALID_SOCKET == hSocket)
  380.             {
  381.                 res = FALSE;
  382.                 continue;
  383.             }
  384.  
  385.             if (m_nFamily == AF_UNSPEC)
  386.             {
  387.                 m_pOwnerSocket->m_SocketData.hSocket = hSocket;
  388.                 m_pOwnerSocket->AttachHandle(hSocket);
  389.                 if (!m_pOwnerSocket->AsyncSelect(m_lEvent))
  390.                 {
  391.                     m_pOwnerSocket->Close();
  392.                     res = FALSE;
  393.                     continue ;
  394.                 }
  395.                 if (m_pOwnerSocket->m_pFirstLayer)
  396.                 {
  397.                     if (WSAAsyncSelect(m_pOwnerSocket->m_SocketData.hSocket, m_pOwnerSocket->GetHelperWindowHandle(), m_pOwnerSocket->m_SocketData.nSocketIndex+WM_SOCKETEX_NOTIFY, FD_READ | FD_WRITE | FD_OOB | FD_ACCEPT | FD_CONNECT | FD_CLOSE) )
  398.                     {
  399.                         m_pOwnerSocket->Close();
  400.                         res = FALSE;
  401.                         continue;
  402.                     }
  403.                 }
  404.                 if (m_pOwnerSocket->m_pendingCallbacks.size())
  405.                     PostMessage(m_pOwnerSocket->GetHelperWindowHandle(), WM_USER + 2, (WPARAM)m_pOwnerSocket->m_SocketData.nSocketIndex, 0);
  406.             }
  407.  
  408.             if (m_nFamily == AF_UNSPEC)
  409.             {
  410.                 m_pOwnerSocket->m_SocketData.nFamily = m_nFamily = res1->ai_family;
  411.                 if (!m_pOwnerSocket->Bind(m_nSocketPort, m_lpszSocketAddress))
  412.                 {
  413.                     m_pOwnerSocket->m_SocketData.nFamily = m_nFamily = AF_UNSPEC;
  414.                     Close();
  415.                     continue;
  416.                 }
  417.             }
  418.  
  419.             if (!( res = ( SOCKET_ERROR != connect(m_pOwnerSocket->GetSocketHandle(), res1->ai_addr, res1->ai_addrlen) ) )
  420.                 && WSAGetLastError() != WSAEWOULDBLOCK)
  421.             {
  422.                 if (hints.ai_family == AF_UNSPEC)
  423.                 {
  424.                     m_nFamily = AF_UNSPEC;
  425.                     Close();
  426.                 }
  427.                 continue ;
  428.             }
  429.  
  430.             m_nFamily = res1->ai_family;
  431.             m_pOwnerSocket->m_SocketData.nFamily = res1->ai_family;
  432.             res = TRUE;
  433.             break;
  434.         }
  435.  
  436.         if (res1)
  437.             res1 = res0->ai_next;
  438.  
  439.         if (res1)
  440.         {
  441.             m_addrInfo = res0;
  442.             m_nextAddr = res1;
  443.         }
  444.         else
  445.             m_pOwnerSocket->p_freeaddrinfo(res0);
  446.  
  447.         if (INVALID_SOCKET == m_pOwnerSocket->GetSocketHandle())
  448.             res = FALSE ;
  449.     }
  450.  
  451.     if (res || WSAGetLastError() == WSAEWOULDBLOCK)
  452.     {
  453.         SetLayerState(connecting);
  454.     }
  455.     return res;
  456. }
  457.  
  458. BOOL CAsyncSocketExLayer::ConnectNext( const SOCKADDR* lpSockAddr, int nSockAddrLen )
  459. {
  460.     ASSERT(GetLayerState()==unconnected);
  461.     ASSERT(m_pOwnerSocket);
  462.     BOOL res;
  463.     if (m_pNextLayer)
  464.         res=m_pNextLayer->Connect(lpSockAddr, nSockAddrLen);
  465.     else
  466.         res = (SOCKET_ERROR!=connect(m_pOwnerSocket->GetSocketHandle(), lpSockAddr, nSockAddrLen));
  467.  
  468.     if (res || WSAGetLastError()==WSAEWOULDBLOCK)
  469.         SetLayerState(connecting);
  470.     return res;
  471. }
  472.  
  473. //Gets the address of the peer socket to which the socket is connected
  474. BOOL CAsyncSocketExLayer::GetPeerName( CStdString& rPeerAddress, UINT& rPeerPort )
  475. {
  476.     return GetPeerNameNext(rPeerAddress, rPeerPort);
  477. }
  478.  
  479. BOOL CAsyncSocketExLayer::GetPeerNameNext( CStdString& rPeerAddress, UINT& rPeerPort )
  480. {
  481.     if (m_pNextLayer)
  482.         return m_pNextLayer->GetPeerName(rPeerAddress, rPeerPort);
  483.     else
  484.     {
  485.         SOCKADDR* sockAddr = 0;
  486.         int nSockAddrLen = 0;
  487.  
  488.         if (m_nFamily == AF_INET6)
  489.         {
  490.             sockAddr = (SOCKADDR*)new SOCKADDR_IN6;
  491.             nSockAddrLen = sizeof(SOCKADDR_IN6);
  492.         }
  493.         else if (m_nFamily == AF_INET)
  494.         {
  495.             sockAddr = (SOCKADDR*)new SOCKADDR_IN;
  496.             nSockAddrLen = sizeof(SOCKADDR_IN);
  497.         }
  498.         else
  499.         {
  500.             WSASetLastError(WSAEOPNOTSUPP);
  501.             return FALSE;
  502.         }
  503.  
  504.         memset(sockAddr, 0, nSockAddrLen);
  505.  
  506.         BOOL bResult = GetPeerName(sockAddr, &nSockAddrLen);
  507.  
  508.         if (bResult)
  509.         {
  510.             if (m_nFamily == AF_INET6)
  511.             {
  512.                 rPeerPort = ntohs(((SOCKADDR_IN6*)sockAddr)->sin6_port);
  513.                 LPTSTR buf = Inet6AddrToString(((SOCKADDR_IN6*)sockAddr)->sin6_addr);
  514.                 rPeerAddress = buf;
  515.                 delete [] buf;
  516.             } 
  517.             else if (m_nFamily == AF_INET)
  518.             {
  519.                 rPeerPort = ntohs(((SOCKADDR_IN*)sockAddr)->sin_port);
  520.                 rPeerAddress = inet_ntoa(((SOCKADDR_IN*)sockAddr)->sin_addr);
  521.             }
  522.             else
  523.             {
  524.                 delete sockAddr;
  525.                 return FALSE;
  526.             }
  527.         }
  528.         delete sockAddr;
  529.  
  530.         return bResult;
  531.     }
  532. }
  533.  
  534. BOOL CAsyncSocketExLayer::GetPeerName( SOCKADDR* lpSockAddr, int* lpSockAddrLen )
  535. {
  536.     return GetPeerNameNext(lpSockAddr, lpSockAddrLen);
  537. }
  538.  
  539. BOOL CAsyncSocketExLayer::GetPeerNameNext( SOCKADDR* lpSockAddr, int* lpSockAddrLen )
  540. {
  541.     if (m_pNextLayer)
  542.         return m_pNextLayer->GetPeerName(lpSockAddr, lpSockAddrLen);
  543.     else
  544.     {
  545.         ASSERT(m_pOwnerSocket);
  546.         if ( !getpeername(m_pOwnerSocket->GetSocketHandle(), lpSockAddr, lpSockAddrLen) )
  547.             return TRUE;
  548.         else
  549.             return FALSE;
  550.     }
  551. }
  552.  
  553. //Gets the address of the sock socket to which the socket is connected
  554. BOOL CAsyncSocketExLayer::GetSockName( CStdString& rSockAddress, UINT& rSockPort )
  555. {
  556.     return GetSockNameNext(rSockAddress, rSockPort);
  557. }
  558.  
  559. BOOL CAsyncSocketExLayer::GetSockNameNext( CStdString& rSockAddress, UINT& rSockPort )
  560. {
  561.     if (m_pNextLayer)
  562.         return m_pNextLayer->GetSockName(rSockAddress, rSockPort);
  563.     else
  564.     {
  565.         SOCKADDR* sockAddr = 0;
  566.         int nSockAddrLen = 0;
  567.  
  568.         if (m_nFamily == AF_INET6)
  569.         {
  570.             sockAddr = (SOCKADDR*)new SOCKADDR_IN6;
  571.             nSockAddrLen = sizeof(SOCKADDR_IN6);
  572.         }
  573.         else if (m_nFamily == AF_INET)
  574.         {
  575.             sockAddr = (SOCKADDR*)new SOCKADDR_IN;
  576.             nSockAddrLen = sizeof(SOCKADDR_IN);
  577.         }
  578.         else
  579.         {
  580.             WSASetLastError(WSAEOPNOTSUPP);
  581.             return FALSE;
  582.         }
  583.  
  584.         memset(sockAddr, 0, nSockAddrLen);
  585.  
  586.         BOOL bResult = GetSockName(sockAddr, &nSockAddrLen);
  587.  
  588.         if (bResult)
  589.         {
  590.             if (m_nFamily == AF_INET6)
  591.             {
  592.                 rSockPort = ntohs(((SOCKADDR_IN6*)sockAddr)->sin6_port);
  593.                 LPTSTR buf = Inet6AddrToString(((SOCKADDR_IN6*)sockAddr)->sin6_addr);
  594.                 rSockAddress = buf;
  595.                 delete [] buf;
  596.             } 
  597.             else if (m_nFamily == AF_INET)
  598.             {
  599.                 rSockPort = ntohs(((SOCKADDR_IN*)sockAddr)->sin_port);
  600.                 rSockAddress = inet_ntoa(((SOCKADDR_IN*)sockAddr)->sin_addr);
  601.             }
  602.             else
  603.             {
  604.                 delete sockAddr;
  605.                 return FALSE;
  606.             }
  607.         }
  608.         delete sockAddr;
  609.  
  610.         return bResult;
  611.     }
  612. }
  613.  
  614. BOOL CAsyncSocketExLayer::GetSockName( SOCKADDR* lpSockAddr, int* lpSockAddrLen )
  615. {
  616.     return GetSockNameNext(lpSockAddr, lpSockAddrLen);
  617. }
  618.  
  619. BOOL CAsyncSocketExLayer::GetSockNameNext( SOCKADDR* lpSockAddr, int* lpSockAddrLen )
  620. {
  621.     if (m_pNextLayer)
  622.         return m_pNextLayer->GetSockName(lpSockAddr, lpSockAddrLen);
  623.     else
  624.     {
  625.         ASSERT(m_pOwnerSocket);
  626.         if ( !getsockname(m_pOwnerSocket->GetSocketHandle(), lpSockAddr, lpSockAddrLen) )
  627.             return TRUE;
  628.         else
  629.             return FALSE;
  630.     }
  631. }
  632.  
  633. void CAsyncSocketExLayer::Init(CAsyncSocketExLayer *pPrevLayer, CAsyncSocketEx *pOwnerSocket)
  634. {
  635.     ASSERT(pOwnerSocket);
  636.     m_pPrevLayer=pPrevLayer;
  637.     m_pOwnerSocket=pOwnerSocket;
  638.     m_pNextLayer=0;
  639. #ifndef NOSOCKETSTATES
  640.     SetLayerState(pOwnerSocket->GetState());
  641. #endif //NOSOCKETSTATES
  642. }
  643.  
  644. int CAsyncSocketExLayer::GetLayerState()
  645. {
  646.     return m_nLayerState;
  647. }
  648.  
  649. void CAsyncSocketExLayer::SetLayerState(int nLayerState)
  650. {
  651.     ASSERT(m_pOwnerSocket);
  652.     int nOldLayerState=GetLayerState();
  653.     m_nLayerState=nLayerState;
  654.     if (nOldLayerState!=nLayerState)
  655.         DoLayerCallback(LAYERCALLBACK_STATECHANGE, GetLayerState(), nOldLayerState);
  656. }
  657.  
  658. void CAsyncSocketExLayer::CallEvent(int nEvent, int nErrorCode)
  659. {
  660.     if (m_nCriticalError)
  661.         return;
  662.     m_nCriticalError = nErrorCode;
  663.     switch (nEvent)
  664.     {
  665.     case FD_READ:
  666.     case FD_FORCEREAD:
  667.         if (GetLayerState()==connecting && !nErrorCode)
  668.         {
  669.             m_nPendingEvents |= nEvent;
  670.             break;
  671.         }
  672.         else if (GetLayerState()==attached)
  673.             SetLayerState(connected);
  674.         if (nEvent & FD_READ)
  675.             m_nPendingEvents &= ~FD_READ;
  676.         else
  677.             m_nPendingEvents &= ~FD_FORCEREAD;
  678.         if (GetLayerState()==connected || nErrorCode)
  679.         {
  680.             if (nErrorCode)
  681.                 SetLayerState(aborted);
  682.             OnReceive(nErrorCode);
  683.         }
  684.         break;
  685.     case FD_WRITE:
  686.         if (GetLayerState()==connecting && !nErrorCode)
  687.         {
  688.             m_nPendingEvents |= nEvent;
  689.             break;
  690.         }
  691.         else if (GetLayerState()==attached)
  692.             SetLayerState(connected);
  693.         m_nPendingEvents &= ~FD_WRITE;
  694.         if (GetLayerState()==connected || nErrorCode)
  695.         {
  696.             if (nErrorCode)
  697.                 SetLayerState(aborted);
  698.             OnSend(nErrorCode);
  699.         }
  700.         break;
  701.     case FD_CONNECT:
  702.         if (GetLayerState()==connecting || GetLayerState() == attached)
  703.         {
  704.             if (!nErrorCode)
  705.                 SetLayerState(connected);
  706.             else
  707.             {
  708.                 if (!m_pNextLayer && m_nextAddr)
  709.                     if (TryNextProtocol())
  710.                     {
  711.                         m_nCriticalError = 0;
  712.                         return;
  713.                     }
  714.                 SetLayerState(aborted);
  715.             }
  716.             m_nPendingEvents &= ~FD_CONNECT;
  717.             OnConnect(nErrorCode);
  718.  
  719.             if (!nErrorCode)
  720.             {
  721.                 if ((m_nPendingEvents & FD_READ) && GetLayerState()==connected)
  722.                     OnReceive(0);
  723.                 if ((m_nPendingEvents & FD_FORCEREAD) && GetLayerState()==connected)
  724.                     OnReceive(0);
  725.                 if ((m_nPendingEvents & FD_WRITE) && GetLayerState()==connected)
  726.                     OnSend(0);
  727.             }
  728.             m_nPendingEvents = 0;
  729.         }
  730.         break;
  731.     case FD_ACCEPT:
  732.         if (GetLayerState()==listening)
  733.         {
  734.             if (nErrorCode)
  735.                 SetLayerState(aborted);
  736.             m_nPendingEvents &= ~FD_ACCEPT;
  737.             OnAccept(nErrorCode);
  738.         }
  739.         break;
  740.     case FD_CLOSE:
  741.         if (GetLayerState()==connected || GetLayerState()==attached)
  742.         {
  743.             if (nErrorCode)
  744.                 SetLayerState(aborted);
  745.             else
  746.                 SetLayerState(closed);
  747.             m_nPendingEvents &= ~FD_CLOSE;
  748.             OnClose(nErrorCode);
  749.         }
  750.         break;
  751.     }
  752. }
  753.  
  754. //Creates a socket
  755. BOOL CAsyncSocketExLayer::Create(UINT nSocketPort, int nSocketType,
  756.             long lEvent, LPCTSTR lpszSocketAddress, int nFamily /*=AF_INET*/, bool reusable /*=false*/)
  757. {
  758.     return CreateNext(nSocketPort, nSocketType, lEvent, lpszSocketAddress, nFamily, reusable);
  759. }
  760.  
  761. BOOL CAsyncSocketExLayer::CreateNext(UINT nSocketPort, int nSocketType, long lEvent, LPCTSTR lpszSocketAddress, int nFamily /*=AF_INET*/, bool reusable /*=false*/)
  762. {
  763.     ASSERT(GetLayerState()==notsock);
  764.     BOOL res = FALSE;
  765.  
  766.     m_nFamily = nFamily;
  767.     
  768.     if (m_pNextLayer)
  769.         res = m_pNextLayer->Create(nSocketPort, nSocketType, lEvent, lpszSocketAddress, nFamily);
  770.     else if (m_nFamily == AF_UNSPEC)
  771.     {
  772.         m_lEvent = lEvent;
  773.         delete [] m_lpszSocketAddress;
  774.         if (lpszSocketAddress && *lpszSocketAddress)
  775.         {
  776.             m_lpszSocketAddress = new TCHAR[_tcslen(lpszSocketAddress) + 1];
  777.             _tcscpy(m_lpszSocketAddress, lpszSocketAddress);
  778.         }
  779.         else
  780.             m_lpszSocketAddress = 0;
  781.         m_nSocketPort = nSocketPort;
  782.         res = TRUE;
  783.     }
  784.     else
  785.     {
  786.         SOCKET hSocket=socket(nFamily, nSocketType, 0);
  787.         if (hSocket == INVALID_SOCKET)
  788.         {
  789.             m_pOwnerSocket->Close();
  790.             return FALSE;
  791.         }
  792.         m_pOwnerSocket->m_SocketData.hSocket=hSocket;
  793.         m_pOwnerSocket->AttachHandle(hSocket);
  794.         if (!m_pOwnerSocket->AsyncSelect(lEvent))
  795.         {
  796.             m_pOwnerSocket->Close();
  797.             return FALSE;
  798.         }
  799.         if (m_pOwnerSocket->m_pFirstLayer)
  800.         {
  801.             if (WSAAsyncSelect(m_pOwnerSocket->m_SocketData.hSocket, m_pOwnerSocket->GetHelperWindowHandle(), m_pOwnerSocket->m_SocketData.nSocketIndex+WM_SOCKETEX_NOTIFY, FD_READ | FD_WRITE | FD_OOB | FD_ACCEPT | FD_CONNECT | FD_CLOSE) )
  802.             {
  803.                 m_pOwnerSocket->Close();
  804.                 return FALSE;
  805.             }
  806.         }
  807.  
  808.         if (reusable && nSocketPort != 0)
  809.         {
  810.             BOOL value = TRUE;
  811.             m_pOwnerSocket->SetSockOpt(SO_REUSEADDR, reinterpret_cast<const void*>(&value), sizeof(value));
  812.         }
  813.  
  814.         if (!m_pOwnerSocket->Bind(nSocketPort, lpszSocketAddress))
  815.         {
  816.             m_pOwnerSocket->Close();
  817.             return FALSE;
  818.         }
  819.         res = TRUE;
  820.     }
  821.     if (res)
  822.         SetLayerState(unconnected);
  823.     return res;
  824. }
  825.  
  826. int CAsyncSocketExLayer::DoLayerCallback(int nType, int nParam1, int nParam2, char* str /*=0*/)
  827. {
  828.     if (!m_pOwnerSocket)
  829.         return 0;
  830.  
  831.     int nError = WSAGetLastError();
  832.  
  833.     t_callbackMsg msg;
  834.     msg.pLayer = this;
  835.     msg.nType = nType;
  836.     msg.nParam1 = nParam1;
  837.     msg.nParam2 = nParam2;
  838.     msg.str = str;
  839.  
  840.     m_pOwnerSocket->AddCallbackNotification(msg);
  841.  
  842.     WSASetLastError(nError);
  843.  
  844.     return 0;
  845. }
  846.  
  847. BOOL CAsyncSocketExLayer::Listen( int nConnectionBacklog)
  848. {
  849.     return ListenNext( nConnectionBacklog);
  850. }
  851.  
  852. BOOL CAsyncSocketExLayer::ListenNext( int nConnectionBacklog)
  853. {
  854.     ASSERT(GetLayerState()==unconnected);
  855.     BOOL res;
  856.     if (m_pNextLayer)
  857.         res=m_pNextLayer->Listen(nConnectionBacklog);
  858.     else
  859.         res=listen(m_pOwnerSocket->GetSocketHandle(), nConnectionBacklog);
  860.     if (res!=SOCKET_ERROR)
  861.     {
  862.         SetLayerState(listening);
  863.     }
  864.     return res!=SOCKET_ERROR;
  865. }
  866.  
  867. BOOL CAsyncSocketExLayer::Accept( CAsyncSocketEx& rConnectedSocket, SOCKADDR* lpSockAddr /*=NULL*/, int* lpSockAddrLen /*=NULL*/ )
  868. {
  869.     return AcceptNext(rConnectedSocket, lpSockAddr, lpSockAddrLen);
  870. }
  871.  
  872. BOOL CAsyncSocketExLayer::AcceptNext( CAsyncSocketEx& rConnectedSocket, SOCKADDR* lpSockAddr /*=NULL*/, int* lpSockAddrLen /*=NULL*/ )
  873. {
  874.     ASSERT(GetLayerState()==listening);
  875.     BOOL res;
  876.     if (m_pNextLayer)
  877.         res=m_pNextLayer->Accept(rConnectedSocket, lpSockAddr, lpSockAddrLen);
  878.     else
  879.     {
  880.         SOCKET hTemp = accept(m_pOwnerSocket->m_SocketData.hSocket, lpSockAddr, lpSockAddrLen);
  881.  
  882.         if (hTemp == INVALID_SOCKET)
  883.             return FALSE;
  884.         VERIFY(rConnectedSocket.InitAsyncSocketExInstance());
  885.         rConnectedSocket.m_SocketData.hSocket=hTemp;
  886.         rConnectedSocket.AttachHandle(hTemp);
  887.         rConnectedSocket.SetFamily(GetFamily());
  888. #ifndef NOSOCKETSTATES
  889.         rConnectedSocket.SetState(connected);
  890. #endif //NOSOCKETSTATES
  891.     }
  892.     return TRUE;
  893. }
  894.  
  895. BOOL CAsyncSocketExLayer::ShutDown(int nHow /*=sends*/)
  896. {
  897.     return ShutDownNext(nHow);
  898. }
  899.  
  900. BOOL CAsyncSocketExLayer::ShutDownNext(int nHow /*=sends*/)
  901. {
  902.     if (m_nCriticalError)
  903.     {
  904.         WSASetLastError(m_nCriticalError);
  905.         return FALSE;
  906.     }
  907.     else if (GetLayerState()==notsock)
  908.     {
  909.         WSASetLastError(WSAENOTSOCK);
  910.         return FALSE;
  911.     }
  912.     else if (GetLayerState()==unconnected || GetLayerState()==connecting || GetLayerState()==listening)
  913.     {
  914.         WSASetLastError(WSAENOTCONN);
  915.         return FALSE;
  916.     }
  917.  
  918.     if (!m_pNextLayer)
  919.     {
  920.         ASSERT(m_pOwnerSocket);
  921.         return shutdown(m_pOwnerSocket->GetSocketHandle(), nHow);
  922.     }
  923.     else
  924.         return m_pNextLayer->ShutDownNext(nHow);
  925. }
  926.  
  927. int CAsyncSocketExLayer::GetFamily() const
  928. {
  929.     return m_nFamily;
  930. }
  931.  
  932. bool CAsyncSocketExLayer::SetFamily(int nFamily)
  933. {
  934.     if (m_nFamily != AF_UNSPEC)
  935.         return false;
  936.     
  937.     m_nFamily = nFamily;
  938.     return true;
  939. }
  940.  
  941. bool CAsyncSocketExLayer::TryNextProtocol()
  942. {
  943.     m_pOwnerSocket->DetachHandle(m_pOwnerSocket->m_SocketData.hSocket);
  944.     closesocket(m_pOwnerSocket->m_SocketData.hSocket);
  945.     m_pOwnerSocket->m_SocketData.hSocket = INVALID_SOCKET;
  946.  
  947.     BOOL ret = FALSE;
  948.     for (; m_nextAddr; m_nextAddr = m_nextAddr->ai_next)
  949.     {
  950.         m_pOwnerSocket->m_SocketData.hSocket = socket(m_nextAddr->ai_family, m_nextAddr->ai_socktype, m_nextAddr->ai_protocol);
  951.  
  952.         if (m_pOwnerSocket->m_SocketData.hSocket == INVALID_SOCKET)
  953.             continue;
  954.  
  955.         m_pOwnerSocket->AttachHandle(m_pOwnerSocket->m_SocketData.hSocket);
  956.         if (!m_pOwnerSocket->AsyncSelect(m_lEvent))
  957.         {
  958.             m_pOwnerSocket->DetachHandle(m_pOwnerSocket->m_SocketData.hSocket);
  959.             closesocket(m_pOwnerSocket->m_SocketData.hSocket);
  960.             m_pOwnerSocket->m_SocketData.hSocket = INVALID_SOCKET;
  961.             continue;
  962.         }
  963.  
  964. #ifndef NOLAYERS
  965.         if (m_pOwnerSocket->m_pFirstLayer)
  966.         {
  967.             if (WSAAsyncSelect(m_pOwnerSocket->m_SocketData.hSocket, m_pOwnerSocket->GetHelperWindowHandle(), m_pOwnerSocket->m_SocketData.nSocketIndex+WM_SOCKETEX_NOTIFY, FD_READ | FD_WRITE | FD_OOB | FD_ACCEPT | FD_CONNECT | FD_CLOSE))
  968.             {
  969.                 m_pOwnerSocket->DetachHandle(m_pOwnerSocket->m_SocketData.hSocket);
  970.                 closesocket(m_pOwnerSocket->m_SocketData.hSocket);
  971.                 m_pOwnerSocket->m_SocketData.hSocket = INVALID_SOCKET;
  972.                 continue;
  973.             }
  974.         }
  975. #endif //NOLAYERS
  976.  
  977.         m_pOwnerSocket->m_SocketData.nFamily = m_nextAddr->ai_family;
  978.         m_nFamily = m_nextAddr->ai_family;
  979.         if (!m_pOwnerSocket->Bind(m_nSocketPort, m_lpszSocketAddress))
  980.         { 
  981.             m_pOwnerSocket->DetachHandle(m_pOwnerSocket->m_SocketData.hSocket);
  982.             closesocket(m_pOwnerSocket->m_SocketData.hSocket);
  983.             m_pOwnerSocket->m_SocketData.hSocket = INVALID_SOCKET;
  984.             continue; 
  985.         }
  986.  
  987.         if (connect(m_pOwnerSocket->GetSocketHandle(), m_nextAddr->ai_addr, m_nextAddr->ai_addrlen) == SOCKET_ERROR && WSAGetLastError() != WSAEWOULDBLOCK)
  988.         {
  989.             m_pOwnerSocket->DetachHandle(m_pOwnerSocket->m_SocketData.hSocket);
  990.             closesocket(m_pOwnerSocket->m_SocketData.hSocket);
  991.             m_pOwnerSocket->m_SocketData.hSocket = INVALID_SOCKET;
  992.             continue;
  993.         }
  994.  
  995.         SetLayerState(connecting);
  996.  
  997.         ret = true;
  998.         break;
  999.     }
  1000.  
  1001.     if (m_nextAddr)
  1002.         m_nextAddr = m_nextAddr->ai_next;
  1003.  
  1004.     if (!m_nextAddr)
  1005.     {
  1006.         m_pOwnerSocket->p_freeaddrinfo(m_addrInfo);
  1007.         m_nextAddr = 0;
  1008.         m_addrInfo = 0;
  1009.     }
  1010.  
  1011.     if (m_pOwnerSocket->m_SocketData.hSocket == INVALID_SOCKET || !ret)
  1012.         return FALSE;
  1013.     else
  1014.         return TRUE;
  1015. }